<template>
	<el-row style="width: 80%; position: relative; top: 60px; margin: 0 auto">
		<el-col style="width: 100%; margin: 0 auto 20px">
			<el-form :inline="true" style="display: flex; justify-content: center">
				<el-row>
					<el-col>
						<el-form-item label-width="5px">
							<el-input v-model="name" clearable placeholder="输入回目名称" @clear="load" />
						</el-form-item>
						<el-form-item label-width="5px">
							<el-button type="primary" :icon="Search" @click="load"></el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-col>
		<el-col style="width: 100%; margin: 0 auto; display: flex; justify-content: center">
			<el-menu :default-active="cid" mode="horizontal" class="category-menu" :ellipsis="false" @select="changeCateogory">
				<el-menu-item key="0" index="0">
					<div class="category-item">
						<el-avatar :size="40" src="/public/bg.jpg"></el-avatar>
						<span class="category-text">全部回目</span>
					</div>
				</el-menu-item>
				<el-menu-item v-for="(item, index) in categoryList" :key="item.id" :index="item.id.toString()">
					<div class="category-item">
						<el-avatar :size="40" :src="item.img || 'https://via.placeholder.com/40'"></el-avatar>
						<span class="category-text">{{ item.name }}</span>
					</div>
				</el-menu-item>
			</el-menu>
		</el-col>
		<!--  表格页面-->
		<el-col>
			<div class="card-container">
				<el-row :gutter="20">
					<el-col v-for="item in tableData" :key="item.id" :span="6">
						<el-card class="card-item" shadow="hover" @click="handleUpdate(item.id)">
							<el-image style="width: 100%; height: 170px; border-radius: 5px" :src="item.img" fit="contain" />
							<div class="card-content">
								<h3 class="card-title">
									{{ item.name }}
								</h3>
								<p class="card-description">{{ item.des }}</p>
							</div>
						</el-card>
					</el-col>
				</el-row>
			</div>
			<!--      分页按钮-->
		</el-col>
		<el-col>
			<div class="pagination">
				<el-pagination
					:current-page="pageNum"
					:page-size="pageSize"
					:page-sizes="[10, 20, 30, 50, 100, 500, 1000]"
					size="small"
					layout="total, sizes, prev, pager, next, jumper"
					:total="Number(total)"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
		</el-col>
	</el-row>
</template>

<script setup>
import { reactive, ref, shallowRef } from 'vue'
import { CircleCloseFilled, Delete, Download, Edit, InfoFilled, Plus, Refresh, Search, Upload } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import downloadExcel from '@/utils/downloads'
import 'md-editor-v3/lib/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import router from '@/router'

const headerTitle = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const multipleSelection = ref([])
const disabled = ref(true)
const dialogVisible = ref(false)
const categoryList = ref([])
const name = ref('')
const cid = ref('')
const $route = router
const formSize = ref('default')
const ruleFormRef = ref()

const form = reactive({
	id: undefined,
	name: undefined,
	cid: undefined,
	img: undefined,
	file: undefined,
	des: undefined,
	content: undefined
})

// 表单校验规则
const rules = reactive({
	name: [{ required: true, message: '必选项不能为空', trigger: 'blur' }],
	cid: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	img: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	file: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	des: [{ required: true, message: '必选项不能为空', trigger: 'blur' }],
	content: [{ required: true, message: '必选项不能为空', trigger: 'blur' }]
})

//新增方法
const handleAdd = async () => {
	headerTitle.value = reactive('新增数据')
	dialogVisible.value = true
}

const handleUpdate = async id => {
	$route.push(`/front/teach/detail?id=${id}`)
}

// 单个删除方法
const handleDel = async id => {
	await request.delete(`/teach/${id}`)
	ElMessage({
		showClose: true,
		message: '删除成功',
		type: 'success'
	})
	await load()
}

// 批量删除方法
const handleBatchDel = async () => {
	const ids = []
	multipleSelection.value.forEach(row => {
		ids.push(row.id)
	})
	await request.delete(`/teach/batch/${ids}`)
	ElMessage({
		showClose: true,
		message: '批量删除成功',
		type: 'success'
	})
	await load()
}

// 分页查询方法（初始化方法，页面加载成功以后就调用的方法）
const load = async () => {
	const res = await request.get('/teach/page', {
		params: {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			name: name.value,
			cid: cid.value
		}
	})
	pageNum.value = res.data.current
	pageSize.value = res.data.size
	total.value = res.data.total
	tableData.value = res.data.records
	//   categoryList
	const rescategory = await request.get(`/category`)
	categoryList.value = rescategory.data
}

// 清空查询数据重置方法
const handleReset = () => {
	name.value = ''
	cid.value = ''
	load()
}
// 修改每页展示的数据量方法
const handleSizeChange = size => {
	pageSize.value = size
	load()
}
// 翻页方法
const handleCurrentChange = current => {
	pageNum.value = current
	load()
}
// 多选按钮处理方法
const handleSelectionChange = val => {
	multipleSelection.value = val
	disabled.value = val.length === 0
}

// 关闭弹框提示方法
const handleClose = done => {
	ElMessageBox.confirm('确定关闭窗口?')
		.then(() => {
			handleResetForm(ruleFormRef.value)
		})
		.then(() => {
			done()
		})
		.catch(() => {
			// catch error
		})
}

// 提交表单校验方法
const handleSubmitForm = async formEl => {
	if (!formEl) {
		return
	}

	await formEl.validate(async (valid, fields) => {
		if (valid) {
			await request({
				method: form.id ? 'put' : 'post',
				url: form.id ? `/teach/${form.id}` : '/teach',
				data: form
			})
			ElMessage({
				showClose: true,
				message: '操作成功',
				type: 'success'
			})
			await handleResetForm(formEl)
		} else {
			console.log('error submit!', fields)
		}
	})
}

// 批量导入读数据写到后端数据库中
const beforeBatchUpload = async file => {
	let fd = new FormData()
	fd.append('file', file)
	await request.post('/teach/batch/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	await load()
}

// 批量导出方法
const handleBatchExport = async () => {
	const ids = multipleSelection.value.map(row => row.id)
	const res = await request(
		{
			url: `/teach/batch/export/${ids}`,
			method: 'get',
			responseType: 'blob'
		} //在请求中加上这一行，特别重要
	)
	downloadExcel(res, '导出数据表')
}

// 取消弹框方法
const handleResetForm = async formEl => {
	if (!formEl) {
		return
	}
	formEl.resetFields()

	Object.assign(form, {
		id: undefined,
		name: undefined,
		cid: undefined,
		img: undefined,
		file: undefined,
		des: undefined,
		content: undefined
	})
	// formEl.clearValidate("img")
	dialogVisible.value = false
	await load()
}

// 文件上传方法
const uploadimg = async file => {
	let fd = new FormData()
	fd.append('file', file)
	const res = await request.post('/file/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	form.img = res.data
	ruleFormRef.value.clearValidate('img')
}

const uploadfile = async file => {
	let fd = new FormData()
	fd.append('file', file)
	const res = await request.post('/file/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	form.file = res.data
	ruleFormRef.value.clearValidate('file')
}

// 文件下载
const dowload = async url => {
	window.open(url)
}

// 富文本文件上传
const onUploadImg = async (files, callback) => {
	let i = 0
	const res = await Promise.all(
		files.map(file => {
			if (i > 0) {
				return false
			}
			return new Promise((rev, rej) => {
				const formdata = new FormData()
				formdata.append('file', file)

				request
					.post('/file/upload', formdata, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					})
					.then(res => {
						i++
						rev(res.data)
					})
					.catch(error => rej(error))
			})
		})
	)
	callback(res)
}

const changeCateogory = async index => {
	cid.value = index === '0' ? '' : index
	await load()
}

const handleDetail = async id => {
	$route.push(`/front/detail?id=${id}`)
}

load()
</script>

<style scoped lang="scss">
.el-form--inline .el-form-item {
	margin-right: 12px;
}

.form_header {
	background-color: #666666;
}

.my-header {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
}

.category-menu {
	border-bottom: 2px solid #f0f0f0;
	padding: 0 20px;
	background: transparent; /* 背景透明 */
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); /* 轻微底部阴影增强层次感 */

	.el-menu-item {
		padding: 0 15px;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		position: relative; /* 用于悬停背景定位 */

		&:before {
			content: '';
			position: absolute;
			bottom: 0;
			left: 50%;
			width: 0;
			height: 2px;
			background-color: #409eff; /* 选中时的底部指示线 */
			transition: width 0.3s ease;
		}

		&:hover {
			background-color: rgba(64, 158, 255, 0.12); /* 悬停半透明背景（比原来明显） */
			transform: translateY(-2px);
			box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15); /* 增强悬停阴影 */

			&:before {
				width: calc(100% - 30px); /* 悬停时显示底部指示线 */
				left: 15px;
			}
		}

		&.is-active {
			.category-text {
				color: #409eff;
				font-weight: 600;
			}
			.el-avatar {
				box-shadow: 0 0 0 2px #409eff;
			}
			&:before {
				width: calc(100% - 30px); /* 选中时固定指示线 */
				left: 15px;
			}
		}
	}
}

.category-item {
	display: flex;
	align-items: center;
	height: 60px; /* 统一菜单项高度 */
	padding: 0 10px;

	.el-avatar {
		margin-right: 8px;
		transition:
			transform 0.3s ease,
			box-shadow 0.3s ease;
	}

	.category-text {
		font-size: 14px;
		color: #333;
		white-space: nowrap; /* 防止文字换行 */
		transition: color 0.3s ease;
	}
}

.category-text {
	font-size: 14px;
	color: #333;
	transition: color 0.3s ease;
}

.el-menu-item.is-active .category-text {
	color: #409eff; /* 选中时文字变蓝 */
}

.card-container {
	padding: 20px 0 100px;
	min-height: 60vh;
}

.card-item {
	margin-bottom: 24px;
	border-radius: 12px;
	overflow: hidden;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	cursor: pointer; /* 添加手指光标 */
	border: 1px solid #ebeef5;

	&:hover {
		transform: translateY(-6px);
		box-shadow: 0 6px 18px rgba(0, 0, 0, 0.12);

		.el-image {
			transform: scale(1.05);
		}

		.card-title {
			color: #409eff;
		}
	}

	.el-image {
		transition: transform 0.3s ease;
		border-radius: 8px 8px 0 0;
	}
}

.card-content {
	padding: 16px;
	background: linear-gradient(to bottom, #ffffff 60%, #fafafa 100%);
}

.card-title {
	font-size: 18px;
	font-weight: 600;
	margin-bottom: 10px;
	color: #303133;
	transition: color 0.2s ease;
	line-height: 1.4;
}

.card-description {
	font-size: 13px;
	color: #606266;
	line-height: 1.6;
	height: 63px; /* 保持三行高度 */
}

.card-meta {
	display: flex;
	align-items: center;
	margin-top: 10px;
}

.meta-text {
	font-size: 12px;
	color: #999;
	margin-left: 8px;
}

.pagination {
	position: fixed;
	bottom: 20px;
	left: 50%;
	transform: translateX(-50%);
	z-index: 1000;
	background: rgba(255, 255, 255, 0.9);
	padding: 8px 20px;
	border-radius: 24px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	display: inline-flex;

	:deep(.el-pagination__total),
	:deep(.el-pagination__jump),
	:deep(.el-pagination__sizes),
	:deep(.btn-prev),
	:deep(.btn-next) {
		color: #333;
	}

	:deep(.el-pager li) {
		color: #333;

		&.is-active {
			color: #409eff;
		}
	}
}

@media (max-width: 768px) {
	.card-container .el-col {
		span: 24;
	}

	.category-menu {
		flex-wrap: wrap;
		justify-content: center;

		.el-menu-item {
			margin-bottom: 8px;
		}
	}
}
</style>
